package com.laobiao.file_netty_lib.netty.server.handler;

import java.io.File;
import java.io.UnsupportedEncodingException;

import com.laobiao.file_netty_lib.exception.FileBaseException;
import com.laobiao.file_netty_lib.netty.server.ServerApplication;
import com.laobiao.file_netty_lib.netty.server.ServerBusiness;
import com.laobiao.file_netty_lib.packet.BasePacket;
import com.laobiao.file_netty_lib.packet.command.ResoultCommand;
import com.laobiao.file_netty_lib.packet.command.Mkdir.MkdirCommand;
import com.laobiao.file_netty_lib.packet.command.fileDelete.FileDeleteCommand;
import com.laobiao.file_netty_lib.util.FileUtil;

import io.netty.channel.ChannelHandlerContext;

public class ServerMkdirBusiness implements ServerBusiness{
	
	private MkdirCommand command;
	
	private File dir;
	
	public ServerMkdirBusiness(ChannelHandlerContext ctx,MkdirCommand command) {
		this.command=command;
		String dirPath = command.getRemoteDirPath();
		if(dirPath==null) {
			ResoultCommand rc =new ResoultCommand(ResoultCommand.ResoultCode.Common.COMM_RESOULT, "目录文件地址不能为空！", false, command.getBusinessGroup());
			ctx.writeAndFlush(rc);
			close();
			throw new FileBaseException("目录文件地址不能为空！", FileBaseException.ERR_PARAM_NULL);
		}else {
			dir=new File(ServerApplication.getServerBasePath()+dirPath);
			try {
				sendData(ctx);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				ResoultCommand rc =new ResoultCommand(ResoultCommand.ResoultCode.Common.COMM_RESOULT, "解析文件失败！", false, command.getBusinessGroup());
				ctx.writeAndFlush(rc);
				close();
				throw new FileBaseException("目录文件地址不存在！", e,FileBaseException.ERR_PARAM_NULL);
			}
		}
	}
	
	private void sendData(ChannelHandlerContext ctx) throws UnsupportedEncodingException {
		try {
			if(!dir.exists()) {
				dir.mkdirs();
			}
			ResoultCommand rc =new ResoultCommand(ResoultCommand.ResoultCode.Common.COMM_RESOULT, "创建文件夹成功！", true, command.getBusinessGroup());
			ctx.writeAndFlush(rc);
		} catch (Exception e) {
			ResoultCommand rc =new ResoultCommand(ResoultCommand.ResoultCode.Common.COMM_RESOULT, "创建文件夹失败！", true, command.getBusinessGroup());
			ctx.writeAndFlush(rc);
		}
		
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void hasPacket(ChannelHandlerContext ctx, BasePacket packet) {
		// TODO Auto-generated method stub
		
	}

}
